package com.hmy.finance.common.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Component
public class CommonCodeGenerator {

    @Autowired
    private RedisTemplate redisTemplate;

    public String getNext(String prefix, String cacheCode) {
        String currentDate = DateUtil.format(new Date(), DatePattern.createFormatter("yyMMdd"));
        RedisAtomicLong aLong = new RedisAtomicLong(cacheCode + currentDate, Objects.requireNonNull(redisTemplate.getConnectionFactory()));
        long andIncrement = aLong.getAndIncrement();
        if (andIncrement == 0) {
            andIncrement = aLong.getAndIncrement();
        }
        //当天过期
        aLong.expireAt(DateUtil.endOfDay(new Date()));
        return prefix + currentDate + String.format("%04d", andIncrement);
    }
}
